#include <nxos.h>

NX_Error PowerBoxBuiltinCat(int argc, char *argv[], char * env)
{
	if (argc == 1) {
        NX_Printf("please input cat file!\n");
		return NX_EINVAL;
	}
	if (argc > 2) {
		NX_Printf("cat: only support 2 argument!\n");
		return NX_EINVAL;
	}

	const char *path = (const char *)argv[1];

	int fd = NX_FileOpen(path, NX_FILE_RDWR, 0);
	if (fd == -1) {
		NX_Printf("cat: file %s not exist!\n", path);
		return NX_ENORES;
	}

	NX_FileStatInfo fstat;
	NX_FileGetStatFromPath(path, &fstat);

    if (!fstat.size) {
        NX_FileClose(fd);
        return NX_EOK;
    }

	char *buf = (char *)NX_MemAlloc(fstat.size);
    if (!buf) {
        NX_FileClose(fd);
        return NX_ENOMEM;
    }

	NX_Size bytes = NX_FileRead(fd, buf, fstat.size);
	NX_FileClose(fd);

	int i = 0;
	while (i < bytes) {
		NX_Printf("%c", buf[i]);
		i++;
	}
    NX_Printf("\n");
	NX_MemFree(buf);

    return NX_EOK;
}
